﻿using Communicate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using BaseDll;
using CommonTools;
using UserData;

namespace StationDemo
{
    public enum ControlType
    {
        Idle,
        StartCmd,
        TestCmd,
        StopCmd
    }
    public class LoadClient
    {

        private static object obj = new object();
        private static LoadClient visionDataMgr;
        /// <summary>
        /// 获取视觉数据管理句柄
        /// </summary>
        /// <returns></returns>
        public static LoadClient GetInstance()
        {
            if (visionDataMgr == null)
            {
                lock (obj)
                {
                    visionDataMgr = new LoadClient();
                    return visionDataMgr;
                }

            }
            else
                return visionDataMgr;
        }
        bool b_heartFlag = false;
        bool b_Islink = false;
        public ControlType control = ControlType.Idle;
        TcpLink Client;
        Thread thread_Recive;
        Thread thread;
        string strIP;
        int nPort;
        List<string> m_InEnd = new List<string>();
        List<string> m_Alarming = new List<string>();
        List<string> m_AlarmEnd = new List<string>();
        bool b_AlreadyEndRecive = false;
        string strEndReciveMsg = "";
        public void Init(string ip, int port)
        {
            strIP = ip;
            nPort = port;
            Client = new TcpLink(1, "TCP", strIP, nPort, 2000, "");
            Client.Open();
            //thread_Recive = new Thread(Recive);
            //thread_Recive.IsBackground = true;
            //thread_Recive.Start();
            Client.RecvStringMessageEvent += Recive;
            thread = new Thread(Run);
            thread.IsBackground = true;
            thread.Start();
        }
        public void Connect()
        {
            int _error = 1;
        Retry:
            
            ;
            if (!Client.Open())
            {
                Client.Close();
                if (_error > 1)
                {
                    Thread.Sleep(1000);
                    goto Retry;
                }
                else if (_error > 10)
                {
                    Thread.Sleep(5000);
                    goto Retry;
                }
                else
                {
                    _error = 0;
                    goto Retry;
                }
            }
        }
        private void Run()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Restart();
            int n_RetryTime = 0;
            while (true)
            {
                try
                {
                    Thread.Sleep(1000);
                    b_heartFlag = false;
                    Send($"HeartBeat");
                    while (true)
                    {
                        if (stopwatch.ElapsedMilliseconds > 3000)
                        {

                            n_RetryTime++;
                            LogHelper.OnTest_ShowLog("Client", $"第{n_RetryTime}次未收到心跳，继续获取", UserData.LogType.Warn);
                            if (n_RetryTime < 3)
                                break;
                            else
                            {
                                LogHelper.OnTest_ShowLog("Client", $"连续三次获取心跳失败，重新连接服务器", UserData.LogType.Err);
                                b_Islink = false;
                                n_RetryTime = 0;
                                Connect();
                                break;
                            }
                        }
                        if (b_heartFlag)
                        {
                            b_Islink = true;
                            n_RetryTime = 0;
                            break;
                        }

                    }
                }
                catch (Exception e)
                {
                    //LogHelper.OnTest_ShowLog(StationName, $"{e}.ToString()", UserData.LogType.Err);
                }
            }
        }
        string ReceiveAllString = "";
        private void Recive(object sender, AsyTcpSocketEventArgs e)
        {
            try
            {

                ReceiveAllString = ReceiveAllString + e.Message;
                if (!ReceiveAllString.Contains("*"))
                    return;
                string str_Restle = ReceiveAllString.Replace("\r\n", "*");
                string[] s_Restle = str_Restle.Split('*');
                for (int i = 0; i < s_Restle.Length - 1; i++)
                {
                    if (s_Restle[i] == "")
                        continue;
                    if (s_Restle[i].Contains("Heart"))
                    {
                        b_heartFlag = true;
                    }
                    else
                    {
                        LogHelper.OnTest_ShowLog("Client", $"TCP接收:{s_Restle[i]}", UserData.LogType.Info);
                    }
                    if (s_Restle[i].Contains("StartCmd"))
                    {
                        control = ControlType.StartCmd;
                    }
                    else if (s_Restle[i].Contains("TestCmd"))
                    {
                        control = ControlType.TestCmd;
                    }
                    else if (s_Restle[i].Contains("StopCmd"))
                    {
                        control = ControlType.StopCmd;
                    }
                }
                ReceiveAllString = s_Restle[s_Restle.Length - 1];


            }
            catch (Exception eX)
            {
                //  LogHelper.OnTest_ShowLog(StationName, $"{e}.ToString()", UserData.LogType.Err);
            }


        }
        object objLock = new object();
        public void Send(string SendStr)
        {
            lock (objLock)
            {
                Thread.Sleep(100);
                Client.WriteString(SendStr + "*");
                if (!SendStr.Contains("Heart"))
                {
                    LogHelper.OnTest_ShowLog("Client", $"TCP发送:{SendStr}", UserData.LogType.Info);
                }

            }
        }
        public bool IsLink()
        {
            return b_Islink;
        }
        /// <summary>
        /// 轮询此控制状态   做完相关工作之后，调用Cmd函数回传数据，若已处理过，直接回传
        /// </summary>
        /// <returns></returns>
        public ControlType ServerControl()
        {
            return control;
        }

        
        public void Cmd_启动完成(bool b_Result)
        {

            if (b_Result)
                Send($"StartOK");
            else
                Send($"StartFail");
            control = ControlType.Idle;
            return;

        }
        public void Cmd_测试完成(bool b_Result)
        {

            if (b_Result)
                Send($"TestOK");
            else
                Send($"TestFail");
            control = ControlType.Idle;
            return;

        }
        public void Cmd_停止完成(bool b_Result)
        {

            if (b_Result)
                Send($"StopOK");
            else
                Send($"StopFail");
            control = ControlType.Idle;
            return;

        }

    }

}
